<template>
  <div class="loading" v-loading="isListLoading" v-if="isListLoading"></div>
  <div class="NewMessageArea">
    <h1 class="title">评论</h1>
    <el-input
      type="textarea"
      :rows="4"
      :placeholder="hint"
      style="margin-bottom: 10px"
      v-model="uerInput"
      ref="uerInputRef"
      maxlength="80"
      show-word-limit
    >
    </el-input>
    <div class="fbBtn">
      <el-button size="small" v-show="hint != '请输入评论'" plain @click="cancelComment">取消</el-button>
      <el-button size="small" type="primary" @click="submitComment" :disabled="isListLoading">发布</el-button>
    </div>
    <!-- 评论 -->
    <div class="comment_pl">
      <!-- 文章回复时的弹出框 -->
      <el-dialog title="个人信息" v-model="showReply" :width="iswidth" top="20vh" @close="dilogClose">
        <ReplyTk @finish="getinput" ref="replyTK"></ReplyTk>
      </el-dialog>
      <el-skeleton v-show="!isCommentLoading" :rows="6" animated />
      <Comment
        v-for="item in usercomment"
        @lookcomment="lookcomment"
        :key="item['_id'] || Math.floor(Math.random() * 1000)"
        @reply="reply"
        :relyNumber="+item.commentNumber"
        :ceid="item['_id']"
      >
        <!-- 头像 -->
        <template v-slot:userimg>
          <el-image style="width: 100%; height: 100%" :src="item.userImg" fit="cover"></el-image>
        </template>
        <!-- 昵称 -->
        <template v-slot:userName>
          {{ item.userName }}
        </template>
        <!-- 发布时间 -->
        <template v-slot:fbTime>
          {{ item.commentTime }}
        </template>
        <!-- 评论内容 -->
        <template v-slot:replyContent>
          {{ item.commentCont }}
        </template>
        <!-- 共有多少回复 -->
        <template v-slot:commentNumber>
          {{ item.commentNumber }}
        </template>

        <!-- 其他人的回复 -->
        <template v-slot:otherComments>
          <!-- 点击查看更多后有一个加载动画 -->
          <div class="loading" style="height: 150px" v-if="!isOtherCommentLoading"></div>

          <Othercomment
            v-show="isOtherCommentLoading"
            v-for="(otheritem, index) in item.othercomment"
            :key="`${item['_id']}-${index}`"
            :ceid="item['_id']"
            :isadmin="otheritem['isadmin']"
            :commentPoint="otheritem.userName"
            :showIpt="otheritem.showIpt"
            :index="index"
            @replyOther="replyOther"
            @handleReply="handleReply(item['_id'], index)"
          >
            <!-- 头像 -->
            <template v-slot:userimg>
              <el-image style="width: 100%; height: 100%" :src="otheritem.userImg" fit="cover"></el-image>
            </template>
            <!-- 昵称 -->
            <template v-slot:userName> {{ otheritem.userName }}</template>
            <!-- 发布时间 -->
            <template v-slot:fbTime> {{ otheritem.commentTime }} </template>
            <!-- 评论内容 -->
            <template v-slot:replyContent>
              {{ otheritem.commentCont }}
            </template>
            <!-- 回复对象 -->
            <template v-slot:commentPoint>{{ otheritem.commentPoint }} </template>
          </Othercomment>
        </template>
      </Comment>

      <el-empty v-if="iscomment" description="暂无评论"></el-empty>
    </div>
  </div>
</template>

<script setup lang="ts">
// 载入评论模块对象
import { uerComments } from './userComments.ts'
import { onMounted, ref, getCurrentInstance, type ComponentPublicInstance } from 'vue'
const proxy: ComponentPublicInstance<any> = getCurrentInstance()?.proxy
//输入框的提示文字
const hint = ref('请输入评论')
// const articleData = ref('')

const uerInput = ref('')

//是否打开回复文章的弹框
const showReply = ref(false)

//当前回复的对象，0代表层主，1代表其他用户
const commentpoin = ref(0)
//当前回复的对象的名称
const commentPoint = ref('')
//层主评论对应的数组
const usercomment = ref([])

// 当前回复的楼层id
const replyceid = ref('')

//文章是否有评论
const iscomment = ref(false)

//文章内容是否已经加载完
// const isArticleLoading = ref(false)

// 文章的评论是否已经加载完
const isCommentLoading = ref(false)

//楼层中其他评论是否已经加载完
const isOtherCommentLoading = ref(false)

// 获取文章数据失败展示
// const errdecripe = ref('')

//是否展示文章读取失败的提示
// const isLoadingOk = ref(false)

//回复的用户头像，昵称
const userImg = ref('')
const userName = ref('')

//回复对话框的款窄
const iswidth = ref('50%')

//同层其他回复是否为管理员回复
const isadmin = ref(false)

//同层回复的对象是否为管理员
const replayObjIsadmin = ref(false)
//当前评论对象之前的评论内容
const oldreplyCon = ref('')
const uerInputRef = ref<any>(null)
//当前展示的评论楼层信息
const currNeedshowCeid = ref(null)
//当前回复框的索引
// const currCeIndex = ref(null)
//当前回复框输入的内容
// const currIptTxt = ref('')
const isListLoading = ref(false)
const replyTK = ref(null)
const props = defineProps({
  articleId: {
    type: String,
    default: ''
  }
})
onMounted(() => {
  getCommentList()
  //根据视口的大小调整回复框的比例
  if (window.innerWidth <= 768) {
    iswidth.value = '85%'
  }
})
const submitComment = () => {
  if (!uerInput.value) {
    proxy.$showMessage({
      content: '评论的内容为空',
      type: 'error'
    })
    return
  }
  showReply.value = true
}
const getinput = (inputData) => {
  userImg.value = inputData.userImg
  userName.value = inputData.userName
  sendComment()
}

//获取层主评论列表
const getCommentList = async () => {
  let comment = new uerComments()
  const result = await comment.getCommentList(props.articleId)
  if (result.length == 0) {
    isCommentLoading.value = true
    iscomment.value = true
  } else {
    isCommentLoading.value = true
    usercomment.value = result.list
  }
}

//根据ceid获取当前楼层的其他评论
const lookcomment = async (ceId: string) => {
  let comment = new uerComments()
  const data = await comment.getOtherCommentList(ceId)
  //查询成功
  isOtherCommentLoading.value = true
  //将得到的数据添加到层主数组中othercomment属性中
  //找到当前数据对应的楼层索引
  let ceindex = 0
  for (let index in usercomment.value) {
    if (usercomment.value[index]['_id'] == ceId) {
      ceindex = index
      break
    }
  }
  //vue无法直接通过数组索引来进行数据修改
  //获取需要展示的这一项
  currNeedshowCeid.value = usercomment.value[ceindex]
  currNeedshowCeid.value.othercomment = data.list
  //为othercomment添加showIpt属性
  currNeedshowCeid.value.othercomment.forEach((item) => {
    item.showIpt = false
  })
  usercomment.value.splice(ceindex, 1, currNeedshowCeid.value)
  //存储当前楼层评论内容
  sessionStorage.setItem(ceId, JSON.stringify(currNeedshowCeid.value))
}
//处理回复按钮,回复其中一个用户，是的同楼层其他用户取消回复
const handleReply = (ceId: string, ceIndex: number) => {
  console.log(`output->ceIndex`, ceIndex)
  let curCeiInfo = JSON.parse(sessionStorage.getItem(ceId))
  //找到当前数据对应的楼层索引
  let ceindex = 0
  for (let index in usercomment.value) {
    if (usercomment.value[index]['_id'] == ceId) {
      ceindex = +index
      break
    }
  }
  usercomment.value[ceindex].othercomment = curCeiInfo.othercomment
  usercomment.value[ceindex].othercomment.forEach((item, index) => {
    if (index == ceIndex) {
      console.log(`output->item.showIpt`, item.showIpt)
      item.showIpt = !item.showIpt
    } else {
      item.showIpt = false
    }
  })
  //存储当前楼层评论内容
  sessionStorage.setItem(ceId, JSON.stringify(usercomment.value[ceindex]))
  console.log(`output->usercomment.value[ceindex].othercomment`, usercomment.value[ceindex].othercomment)
}
// 发送评论
const sendComment = async () => {
  if (uerInput.value == '') {
    proxy.$showMessage({
      content: '发送的内容为空',
      type: 'error'
    })
    return
  }
  isListLoading.value = true
  //当前回复的对象是层主
  if (commentpoin.value == 0) {
    let comment = new uerComments(props.articleId, userImg.value, userName.value, uerInput.value, '', '', isadmin.value)
    const data = await comment.sendComment(comment.sendData)
    console.log(data, '用户评论')
    uerInput.value = ''
    proxy.$showMessage({
      content: '回复成功',
      type: 'success'
    })
    isListLoading.value = false
    // 回复成功后可以将数据添加到页面上，提升用户体验this.articleId
    usercomment.value.push(data)
    iscomment.value = false
  }
  //当前回复的对象是其他
  if (commentpoin.value == 1) {
    let comment = new uerComments(props.articleId, userImg.value, userName.value, uerInput.value, commentPoint.value, replyceid.value, isadmin.value)
    comment.sendData.replayObjIsadmin = replayObjIsadmin.value
    comment.sendData.oldreplyCon = oldreplyCon.value
    const data = await comment.sendOtherComment(comment.sendData)
    //请求失败则终止
    if (!data) {
      return
    }
    proxy.$showMessage({
      content: '回复成功',
      type: 'success'
    })
    isListLoading.value = false
    hint.value = '请输入评论'
    commentpoin.value = 0
    uerInput.value = ''
    // 回复成功后可以将数据添加到页面上，提升用户体验
    //找到当前数据对应的楼层索引
    let ceindex
    for (let index in usercomment.value) {
      if (usercomment.value[index]['_id'] == data.ceID) {
        ceindex = index
        break
      }
    }
    let needshow = usercomment.value[ceindex]
    needshow.commentNumber += 1
    usercomment.value.splice(ceindex, 1, needshow)
    lookcomment(data.ceID)
  }
}

// 回复层主
const reply = (replyUser) => {
  replyceid.value = replyUser.ceId
  oldreplyCon.value = replyUser.oldreplyCon
  hint.value = `回复:${replyUser.name}`
  uerInputRef.value.focus()
  commentpoin.value = 1
  replayObjIsadmin.value = false
  commentPoint.value = replyUser.name
}

//回复其他用户
const replyOther = (replyUser) => {
  replyceid.value = replyUser.ceId
  oldreplyCon.value = replyUser.oldreplyCon
  commentpoin.value = 1
  replayObjIsadmin.value = false
  uerInput.value = replyUser.firstComments
  commentPoint.value = replyUser.commentPoint
  if (replyUser.isadmin) {
    replayObjIsadmin.value = true
  }
  showReply.value = true
}

// 取消评论
const cancelComment = () => {
  hint.value = '请输入评论'
  uerInput.value = ''
  commentpoin.value = 0
  replayObjIsadmin.value = false
}
//关闭信息录入弹框
const dilogClose = () => {
  //清空步骤条
  replyTK.value.clearStep()
}
</script>

<style lang="scss" scoped>
.readArtile {
  max-width: 1024px;
  margin: 0px auto;
  // padding: 0px 8px;

  .cont {
    background: white;
    // box-shadow: 0 0 6px rgba(0, 0, 0, 0.1);
    overflow: hidden;
    padding: 20px;
    padding-top: 30px;
  }
}

.feedback {
  height: 150px;
  // border-bottom: 1px solid #e4e7ed;
  margin-top: 50px;
  display: flex;
  // justify-content: space-between;
  justify-content: center;
  align-items: center;

  .previous {
    overflow: hidden;

    .ico {
      cursor: pointer;
      height: 40px;
      color: #909399;

      line-height: 40px;

      &:hover {
        color: rgb(95, 95, 95);
      }
    }
  }

  .next {
    overflow: hidden;

    .ico {
      height: 40px;
      color: #909399;
      cursor: pointer;
      line-height: 40px;

      &:hover {
        color: rgb(95, 95, 95);
      }
    }
  }

  .giveLike {
    height: 40px;
    width: 80px;
    cursor: pointer;
    // background-color: rgb(64, 158, 255);
    border: 1px solid #909399;

    border-radius: 20px;
    color: #909399;
    text-align: center;
    line-height: 40px;

    &:hover {
      background-color: #909399;
      color: white;
    }
  }
}

.comment_pl {
  margin-top: 30px;

  .title {
    font-weight: 600;
    font-size: 24px;
    color: #606266;
    padding: 25px 0;
  }

  .fbBtn {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 50px;
  }

  ::v-deep(.el-dialog) {
    padding-bottom: 45px;
  }
}

@media (max-width: 768px) {
  .readArtile {
    .cont {
      padding: 15px;
      padding-top: 10px;
    }
  }
}

.loading {
  position: fixed;
  top: 50%;
  left: 50%;
  width: 100vw;
  height: 100vh;
  transform: translate(-50%, -50%);
  z-index: 999;
}
</style>
